package think.thread.sychron;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

class ProductChannel {

	private ArrayBlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<Integer>(
			10);

	public void addProduct(Integer product) {
		System.out.println("add product " + product);
		blockingQueue.add(product);
	}

	public void takeProduct() throws Exception {
		int product = blockingQueue.take();
		System.out.println("take the product " + product);
	}

}

class Producer implements Runnable {

	private ProductChannel channel;

	public Producer(ProductChannel channel) {
		this.channel = channel;
	}

	Random rand = new Random();

	public void run() {
		try {
			while (!Thread.interrupted()) {
				channel.addProduct(rand.nextInt(10));
				TimeUnit.MILLISECONDS.sleep(100);
			}
		} catch (Exception e) {
			System.out.println("producer exit via interrupted");
		}
	}

}

class Consumer implements Runnable {

	private ProductChannel channel;

	public Consumer(ProductChannel channel) {
		this.channel = channel;
	}

	public void run() {
		try {
			while (!Thread.interrupted()) {
				channel.takeProduct();
				TimeUnit.MILLISECONDS.sleep(50);
			}
		} catch (Exception e) {
			System.out.println("consumer exit via interrupted");
		}
	}

}

public class ConsumerAndProducer {

	public static void main(String[] args) throws Exception {
		ProductChannel channel = new ProductChannel();

		Thread thread1 = new Thread(new Producer(channel));
		Thread thread2 = new Thread(new Consumer(channel));

		thread2.start();
		TimeUnit.SECONDS.sleep(1);

		thread1.start();

		TimeUnit.SECONDS.sleep(3);
		thread1.interrupt();
		thread2.interrupt();
	}

}
